class Solution:
    def longestSubarray(self, nums: list, limit: int) -> int:
        def binary1(array, num):
            if len(array) == 0:
                return 0
            if array[0] > num:
                return 0
            if array[-1] < num:
                return len(array)
            left = 0
            right = len(array) - 1
            while left < right:
                mid = (left + right) // 2
                if array[mid] < num:
                    left = mid + 1
                else:
                    right = mid
            return right

        def binary2(array, num):
            left = 0
            right = len(array) - 1
            while left <= right:
                mid = (left + right) // 2
                if array[mid] < num:
                    left = mid + 1
                elif array[mid] > num:
                    right = mid - 1
                else:
                    return mid

            return -1

        array = []
        left = 0
        right = 0
        res = 0
        while right < len(nums):
            index = binary1(array, nums[right])
            if index == len(array):
                array.append(nums[right])
            else:
                array.insert(index, nums[right])
            absRes = array[-1] - array[0]
            while absRes > limit:
                index = binary2(array, nums[left])
                del array[index]
                left += 1
                absRes = array[-1] - array[0]
            res = max(res, right - left + 1)
            right += 1
        return res
